package com.mulesoft.domain.analyzer;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.mulesoft.domain.analyzer.structure.GraphList;
import com.mulesoft.domain.analyzer.structure.Pair;

public class WaysByStepWithDistanceCalculator {

		private GraphList graph;

		public static class PathInfo {
			String path;
			public Integer length;
		}
		
		public WaysByStepWithDistanceCalculator(String input) {
			this.graph = new GraphList(input);
		}
		
		public Set<PathInfo> calculateWays(char current, char destination, int length) {
			Set<PathInfo> sol= new HashSet<PathInfo>();
			if (length == 0 && current == destination) {
				PathInfo data = new PathInfo();
				data.length = 0;
				data.path = ""+destination;
				sol.add(data);
				return sol;
			} 
			if (length == 0 && current != destination) {
				return sol;
			}
			// length > 0
			List<Pair<Character, Integer>> neighbors = graph.getNeighbors(current);
			for (Pair<Character, Integer> neighbor : neighbors) {
				Set<PathInfo> preWays = calculateWays(neighbor.getFirst(), destination, length - 1);
				if (preWays.isEmpty()) {
					continue;
				}
				// ways were found.
				sol.addAll(prefix(current, neighbor.getSecond(),preWays));
			}
			return sol;
		}
		
		private Set<PathInfo> prefix(char current, int offset, Set<PathInfo> preWays) {
			Set<PathInfo> withPrefix = new HashSet<PathInfo>();
			for (PathInfo preWay : preWays) {
				PathInfo data = new PathInfo();
				data.path = current + "," +preWay.path;
				data.length =	offset + preWay.length;	
				withPrefix.add(data);
			}
			return withPrefix;
		}

}
